package user;

import java.util.HashSet;
import java.util.Set;
import org.apache.struts2.ServletActionContext;
import role.Role;
import role.RoleDao;
import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private boolean isupdate=true;
	private User user=new User();
	private UserDao userDao;
	private Role role=new Role();
	private RoleDao roleDao;
	
	public boolean isIsupdate() {
		return isupdate;
	}
	public void setIsupdate(boolean isupdate) {
		this.isupdate = isupdate;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public UserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}
	public RoleDao getRoleDao() {
		return roleDao;
	}
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
	public static long getSerialVersionUID() {
		return serialVersionUID;
	}
	
	public String register(){
		Set<Role> roleSet=new HashSet<Role>();
		this.role=this.roleDao.findById(2l);
		roleSet.add(this.role);
		if(user.getId()==null){
			this.user.setUser_role(roleSet);
			userDao.create(user);
			ServletActionContext.getRequest().getSession().setAttribute("user",this.user);
		}else{
			User temp=(User)ServletActionContext.getRequest().getSession().getAttribute("user");
			this.user.setUser_account(temp.getUser_account());
			this.user.setUser_role(roleSet);
			userDao.update(user);
			ServletActionContext.getRequest().getSession().setAttribute("user",this.user);
		}
		return SUCCESS;
	}
	public void validateRegister() {
		if(user.getId()==null){
			if(userDao.isUniqueUserAccount(user.getUser_account())!=null){
				this.addFieldError("user.user_account", "该会员名称已被注册");
			}
			if (userDao.isUniqueUserEmail(user.getUser_email())!=null) {
				this.addFieldError("user.user_email", "该邮箱已被注册");
			}
		}else{
			if(userDao.isUniqueUserAccount(user.getUser_account())!=null){
				if(userDao.isUniqueUserAccount(user.getUser_account()).getId().equals(user.getId())){
					System.out.println("没有改用户名称");
				}else{
					this.addFieldError("user.user_account", "该会员名称已被使用");
				}
			}
			if(userDao.isUniqueUserEmail(user.getUser_email())!=null){
				if(userDao.isUniqueUserEmail(user.getUser_email()).getId().equals(user.getId())){
					System.out.println("没有改使用的邮箱");
				}else{
					this.addFieldError("user.user_email", "该邮箱已被使用");
				}
			}
		}
	}
	public String input(){
		return "input";
	}
	public String execute(){
		return SUCCESS;
	}
}
